package com.isnoam.calendar.view

import android.content.Context
import android.util.AttributeSet
import com.isnoam.calendar.base.BaseCalendarView
import com.isnoam.calendar.base.BaseMonthView
import com.isnoam.calendar.bean.DateInfo
import com.isnoam.calendar.bean.ViewAttrs
import com.isnoam.calendar.listener.OnDateRangeSelectedListener
import com.isnoam.calendar.listener.OnDateSelectedListener
import com.isnoam.calendar.view.month.WeekMonthView
import java.util.*

/**
 * 按星期选择日期控件
 */
class WeekCalendarView(
    context: Context, attrs: AttributeSet
) : BaseCalendarView(context, attrs) {

    private var listener: OnDateRangeSelectedListener? = null

    /**
     * 设置选中日期
     */
    fun setSelectedDate(selectedDate: DateInfo) {
        setDateRange(selectedTimeInMillis = selectedDate.timeInMillis())
    }

    /**
     * 创建月份
     */
    override fun createMonthView(
        position: Int, currentMonth: Calendar, viewAttrs: ViewAttrs
    ): BaseMonthView {
        val monthView = WeekMonthView(context, currentMonth, position, viewAttrs)
        monthView.selectedDate = DateInfo().toDate(selectedDate)
        monthView.onDateSelectedListener = object : OnDateSelectedListener {
            override fun onDateSelected(
                dateInfo: DateInfo, changeMonth: Boolean, monthPosition: Int
            ) {
                listener?.let {
                    it(
                        this@WeekCalendarView,
                        dateInfo,
                        monthView.startDateItem?.date!!,
                        monthView.endDateItem?.date!!
                    )
                }
                updateDateSelected(dateInfo, changeMonth, monthPosition)
            }
        }
        return monthView
    }

    fun setOnDateRangeSelectedListener(listener: OnDateRangeSelectedListener) {
        this.listener = listener
    }
}